<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="原文：Why doesn’t TypeScript properly type Object.keys">
<meta property="og:type" content="article">
<meta property="og:title" content="为什么Object.keys不能正确地类型推导">
<meta property="og:url" content="https://wyatex.online/TypeScript/%E4%B8%BA%E4%BB%80%E4%B9%88Object-keys%E4%B8%8D%E8%83%BD%E6%AD%A3%E7%A1%AE%E5%9C%B0%E7%B1%BB%E5%9E%8B%E6%8E%A8%E5%AF%BC/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="原文：Why doesn’t TypeScript properly type Object.keys">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-07-25T09:55:56.000Z">
<meta property="article:modified_time" content="2023-09-15T09:59:22.600Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="TypeScript">
<meta property="article:tag" content="翻译">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://wyatex.online/TypeScript/%E4%B8%BA%E4%BB%80%E4%B9%88Object-keys%E4%B8%8D%E8%83%BD%E6%AD%A3%E7%A1%AE%E5%9C%B0%E7%B1%BB%E5%9E%8B%E6%8E%A8%E5%AF%BC/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/TypeScript/%E4%B8%BA%E4%BB%80%E4%B9%88Object-keys%E4%B8%8D%E8%83%BD%E6%AD%A3%E7%A1%AE%E5%9C%B0%E7%B1%BB%E5%9E%8B%E6%8E%A8%E5%AF%BC/","path":"TypeScript/为什么Object-keys不能正确地类型推导/","title":"为什么Object.keys不能正确地类型推导"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>为什么Object.keys不能正确地类型推导 | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#TypeScript%E4%B8%AD%E7%9A%84%E7%BB%93%E6%9E%84%E7%B1%BB%E5%9E%8B"><span class="nav-number">1.</span> <span class="nav-text">TypeScript中的结构类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%8D%E5%AE%89%E5%85%A8%E5%9C%B0%E4%BD%BF%E7%94%A8Object-keys"><span class="nav-number">1.1.</span> <span class="nav-text">不安全地使用Object.keys</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%A9%E7%94%A8%E7%BB%93%E6%9E%84%E7%B1%BB%E5%9E%8B"><span class="nav-number">1.2.</span> <span class="nav-text">利用结构类型</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    相关文章
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/%E5%89%8D%E7%AB%AF/js%E7%AC%94%E8%AE%B0%EF%BC%9A%E5%AF%B9%E8%B1%A1-2/" rel="bookmark">
        <time class="popular-posts-time">2020-09-11</time>
        <br>
      js笔记：对象-2
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/JavaScript/const-%E5%92%8C-Object-freeze-%E7%9A%84%E5%8C%BA%E5%88%AB/" rel="bookmark">
        <time class="popular-posts-time">2020-11-19</time>
        <br>
      const 和 Object.freeze() 的区别
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/TypeScript/%E4%B8%BA%E4%BB%80%E4%B9%88Object-keys%E4%B8%8D%E8%83%BD%E6%AD%A3%E7%A1%AE%E5%9C%B0%E7%B1%BB%E5%9E%8B%E6%8E%A8%E5%AF%BC/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="为什么Object.keys不能正确地类型推导 | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          为什么Object.keys不能正确地类型推导
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-07-25 17:55:56" itemprop="dateCreated datePublished" datetime="2023-07-25T17:55:56+08:00">2023-07-25</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-09-15 17:59:22" itemprop="dateModified" datetime="2023-09-15T17:59:22+08:00">2023-09-15</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/TypeScript/" itemprop="url" rel="index"><span itemprop="name">TypeScript</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>原文：<a target="_blank" rel="noopener" href="https://alexharri.com/blog/typescript-structural-typing">Why doesn’t TypeScript properly type Object.keys</a></p>
<span id="more"></span>

<p>如果你写过一段时间的TypeScript，你可能会遇到这种情况</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">Options</span> &#123;</span><br><span class="line">  <span class="attr">hostName</span>: <span class="built_in">string</span>;</span><br><span class="line">  <span class="attr">port</span>: <span class="built_in">number</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">validateOptions</span> (<span class="attr">options</span>: <span class="title class_">Options</span>) &#123;</span><br><span class="line">  <span class="title class_">Object</span>.<span class="title function_">keys</span>(options).<span class="title function_">forEach</span>(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (options[key] == <span class="literal">null</span>) &#123; <span class="comment">// Expression of type &#x27;string&#x27; can&#x27;t be used to index type &#x27;Options&#x27;.</span></span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">`Missing option <span class="subst">$&#123;key&#125;</span>`</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个错误似乎毫无意义。我们使用<code>options</code>的键来访问<code>options</code>。为什么TypeScript不能解决这个问题呢?</p>
<p>我们可以通过 <code>Object.keys(options)</code> 到 <code>(keyof typeof options)[]</code> 的强制转换来规避这个问题</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> keys = <span class="title class_">Object</span>.<span class="title function_">keys</span>(options) <span class="keyword">as</span> (keyof <span class="keyword">typeof</span> options)[];</span><br><span class="line">keys.<span class="title function_">forEach</span>(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (options[key] == <span class="literal">null</span>) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">`Missing option <span class="subst">$&#123;key&#125;</span>`</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>但为什么这是一个问题呢?</p>
<p>如果我们访问<code>Object.keys</code>的类型定义，能看到：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// typescript/lib/lib.es5.d.ts</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">Object</span> &#123;</span><br><span class="line">  <span class="title function_">keys</span>(<span class="attr">o</span>: <span class="built_in">object</span>): <span class="built_in">string</span>[];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>类型定义非常简单。接受<code>object</code>并返回<code>string[]</code>。</p>
<p>让这个方法接受一个泛型参数<code>T</code>并返回<code>(keyof T)[]</code>是非常容易的。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Object</span> &#123;</span><br><span class="line">  keys&lt;T <span class="keyword">extends</span> <span class="built_in">object</span>&gt;(<span class="attr">o</span>: T): (keyof T)[];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果<code>Object.keys</code>是这样定义的，我们就不会遇到类型错误。</p>
<p>看起来我们应该将<code>Object</code>定义这样。但是TypeScript有很好的理由不这样做。原因与TypeScript的<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Structural_type_system">结构类型系统</a>有关。</p>
<h2 id="TypeScript中的结构类型"><a href="#TypeScript中的结构类型" class="headerlink" title="TypeScript中的结构类型"></a>TypeScript中的结构类型</h2><p>当属性丢失或类型错误时，TypeScript会发出警告。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">saveUser</span>(<span class="params">user: &#123; name: <span class="built_in">string</span>, age: <span class="built_in">number</span> &#125;</span>) &#123;&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> user1 = &#123; <span class="attr">name</span>: <span class="string">&quot;Alex&quot;</span>, <span class="attr">age</span>: <span class="number">25</span> &#125;;</span><br><span class="line"><span class="title function_">saveUser</span>(user1); <span class="comment">// OK!</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> user2 = &#123; <span class="attr">name</span>: <span class="string">&quot;Sarah&quot;</span> &#125;;</span><br><span class="line"><span class="title function_">saveUser</span>(user2); <span class="comment">// Property &#x27;age&#x27; is missing in type &#123; name: string &#125;.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> user3 = &#123; <span class="attr">name</span>: <span class="string">&quot;John&quot;</span>, <span class="attr">age</span>: <span class="string">&#x27;34&#x27;</span> &#125;;</span><br><span class="line"><span class="title function_">saveUser</span>(user3); <span class="comment">// Types of property &#x27;age&#x27; are incompatible. Type &#x27;string&#x27; is not assignable to type &#x27;number&#x27;.</span></span><br></pre></td></tr></table></figure>

<p>然而，如果我们提供了多余的属性，TypeScript也不会报错。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">saveUser</span>(<span class="params">user: &#123; name: <span class="built_in">string</span>, age: <span class="built_in">number</span> &#125;</span>) &#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> user = &#123; <span class="attr">name</span>: <span class="string">&quot;Alex&quot;</span>, <span class="attr">age</span>: <span class="number">25</span>, <span class="attr">city</span>: <span class="string">&quot;Reykjavík&quot;</span> &#125;;</span><br><span class="line"><span class="title function_">saveUser</span>(user); <span class="comment">// Not a type error</span></span><br></pre></td></tr></table></figure>

<p>这是结构类型系统的预期行为,如果<code>A</code>是<code>B</code>的超集，类型<code>A</code>可赋值给<code>B</code>（即<code>A</code>包含<code>B</code>中的所有属性）。</p>
<p>然而，如果A是B的真超集(即A比B有更多的属性),那么A可以赋值给B，但是B不能赋给A。</p>
<p>这些都很抽象，所以让我们来看一个具体的例子。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">type A = &#123; foo: number, bar: number &#125;;</span><br><span class="line">type B = &#123; foo: number &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">const a1: A = &#123; foo: 1, bar: 2 &#125;;</span><br><span class="line">const b1: B = &#123; foo: 3 &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">const b2: B = a1;</span><br><span class="line">const a2: A = b1; // Property &#x27;bar&#x27; is missing in type &#x27;B&#x27; but required in type &#x27;A&#x27;.</span><br></pre></td></tr></table></figure>

<p>关键的结论是，当我们有一个<code>T</code>类型的对象时，我们所知道的关于这个对象的一切就是它至少包含了<code>T</code>中的属性。</p>
<p>我们不知道我们是否有确切的<code>T</code>，这就是为什么<code>Object.keys</code>的类型会是这样。让我们举个例子。</p>
<h3 id="不安全地使用Object-keys"><a href="#不安全地使用Object-keys" class="headerlink" title="不安全地使用Object.keys"></a>不安全地使用Object.keys</h3><p>假设我们正在为创建一个新用户注册的界面。我们有一个现有的<code>User</code>接口，看起来像这样:</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">User</span> &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="built_in">string</span>;</span><br><span class="line">  <span class="attr">password</span>: <span class="built_in">string</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在将用户保存到数据库之前，我们要确保用户对象是有效的。</p>
<ul>
<li><code>name</code>不能为空。</li>
<li><code>password</code>至少为6个字符。</li>
</ul>
<p>因此，我们创建一个<code>validators</code>对象，其中包含<code>User</code>中的每个属性的验证函数</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> validators = &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="function">(<span class="params">name: <span class="built_in">string</span></span>) =&gt;</span> name.<span class="property">length</span> &lt; <span class="number">1</span></span><br><span class="line">    ? <span class="string">&quot;Name must not be empty&quot;</span></span><br><span class="line">    : <span class="string">&quot;&quot;</span>,</span><br><span class="line">  <span class="attr">password</span>: <span class="function">(<span class="params">password: <span class="built_in">string</span></span>) =&gt;</span> password.<span class="property">length</span> &lt; <span class="number">6</span></span><br><span class="line">    ? <span class="string">&quot;Password must be at least 6 characters&quot;</span></span><br><span class="line">    : <span class="string">&quot;&quot;</span>,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>然后，我们创建一个 <code>validateUser</code> 函数，通过这些验证器运行 <code>User</code> 对象</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">validateUser</span>(<span class="params">user: User</span>) &#123;</span><br><span class="line">  <span class="comment">// Pass user object through the validators</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因为我们想要验证<code>user</code>中的每个属性，所以可以使用<code>Object.keys</code>遍历<code>user</code>中的属性</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">validateUser</span>(<span class="params">user: User</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> error = <span class="string">&quot;&quot;</span>;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">of</span> <span class="title class_">Object</span>.<span class="title function_">keys</span>(user)) &#123;</span><br><span class="line">    <span class="keyword">const</span> validate = validators[key];</span><br><span class="line">    error ||= <span class="title function_">validate</span>(user[key]);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> error;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意:在这个代码块中有类型错误，我现在隐藏。我们稍后再谈。</p>
</blockquote>
<p>这种方法的问题是，<code>user</code>对象可能包含<code>validators</code>中不存在的属性。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">User</span> &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="built_in">string</span>;</span><br><span class="line">  <span class="attr">password</span>: <span class="built_in">string</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">validateUser</span>(<span class="params">user: User</span>) &#123;&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> user = &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="string">&#x27;Alex&#x27;</span>,</span><br><span class="line">  <span class="attr">password</span>: <span class="string">&#x27;1234&#x27;</span>,</span><br><span class="line">  <span class="attr">email</span>: <span class="string">&quot;alex@example.com&quot;</span>,</span><br><span class="line">&#125;;</span><br><span class="line"><span class="title function_">validateUser</span>(user); <span class="comment">// OK!</span></span><br></pre></td></tr></table></figure>

<p>即使<code>User</code>没有指定<code>email</code>属性，这也不是类型错误，因为结构类型允许提供无关的属性。</p>
<p>在运行时，<code>email</code>属性将导致<code>validators</code>未定义，并在调用时抛出错误。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">of</span> <span class="title class_">Object</span>.<span class="title function_">keys</span>(user)) &#123;</span><br><span class="line">  <span class="keyword">const</span> validate = validators[key];</span><br><span class="line">  error ||= <span class="title function_">validate</span>(user[key]); <span class="comment">// TypeError: &#x27;validate&#x27; is not a function.</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>幸运的是，TypeScript在这段代码有机会运行之前就发出了类型错误。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">of</span> <span class="title class_">Object</span>.<span class="title function_">keys</span>(user)) &#123;</span><br><span class="line">  <span class="keyword">const</span> validate = validators[key]; <span class="comment">// Expression of type &#x27;string&#x27; can&#x27;t be used to index type &#x27;&#123; name: ..., password: ... &#125;&#x27;.</span></span><br><span class="line">  error ||= <span class="title function_">validate</span>(user[key]); <span class="comment">// Expression of type &#x27;string&#x27; can&#x27;t be used to index type &#x27;User&#x27;.</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在我们知道为什么<code>Object.keys</code>的类型是这样了。它迫使我们承认对象可能包含类型系统不知道的属性。</p>
<p>有了关于结构类型及其缺陷的新知识，让我们来看看如何有效地利用结构类型。</p>
<h3 id="利用结构类型"><a href="#利用结构类型" class="headerlink" title="利用结构类型"></a>利用结构类型</h3><p>结构类型提供了很大的灵活性。它允许接口准确地声明它们所需要的属性。我想通过一个例子来说明这一点。</p>
<p>假设我们编写了一个函数，解析<code>KeyboardEvent</code>并返回要触发的快捷方式。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">getKeyboardShortcut</span>(<span class="params">e: KeyboardEvent</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span> (e.<span class="property">key</span> === <span class="string">&quot;s&quot;</span> &amp;&amp; e.<span class="property">metaKey</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;save&quot;</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (e.<span class="property">key</span> === <span class="string">&quot;o&quot;</span> &amp;&amp; e.<span class="property">metaKey</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;open&quot;</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>为了确保代码按预期工作，我们编写了一些单元测试</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">expect</span>(<span class="title function_">getKeyboardShortcut</span>(&#123; <span class="attr">key</span>: <span class="string">&quot;s&quot;</span>, <span class="attr">metaKey</span>: <span class="literal">true</span> &#125;))</span><br><span class="line">  .<span class="title function_">toEqual</span>(<span class="string">&quot;save&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="title function_">expect</span>(<span class="title function_">getKeyboardShortcut</span>(&#123; <span class="attr">key</span>: <span class="string">&quot;o&quot;</span>, <span class="attr">metaKey</span>: <span class="literal">true</span> &#125;))</span><br><span class="line">  .<span class="title function_">toEqual</span>(<span class="string">&quot;open&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="title function_">expect</span>(<span class="title function_">getKeyboardShortcut</span>(&#123; <span class="attr">key</span>: <span class="string">&quot;s&quot;</span>, <span class="attr">metaKey</span>: <span class="literal">false</span> &#125;))</span><br><span class="line">  .<span class="title function_">toEqual</span>(<span class="literal">null</span>);</span><br></pre></td></tr></table></figure>

<p>看起来不错，但是TypeScript会报错</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">getKeyboardShortcut</span>(&#123; <span class="attr">key</span>: <span class="string">&quot;s&quot;</span>, <span class="attr">metaKey</span>: <span class="literal">true</span> &#125;);</span><br><span class="line"><span class="comment">// Type &#x27;&#123; key: string; metaKey: true; &#125;&#x27; is missing the following properties from type &#x27;KeyboardEvent&#x27;: altKey, charCode, code, ctrlKey, and 37 more.</span></span><br></pre></td></tr></table></figure>

<p>指定所有37个附加属性将会非常杂乱，所以这是不可能的。</p>
<p>我们可以通过将参数强制转换为<code>KeyboardEvent</code>来解决这个问题</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">getKeyboardShortcut</span>(&#123; <span class="attr">key</span>: <span class="string">&quot;s&quot;</span>, <span class="attr">metaKey</span>: <span class="literal">true</span> &#125; <span class="keyword">as</span> <span class="title class_">KeyboardEvent</span>);</span><br></pre></td></tr></table></figure>

<p>但这可能会掩盖可能发生的其他类型错误。</p>
<p>相反，我们可以更新<code>getKeyboardShortcut</code>，只声明它需要从事件中获取的属性。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">KeyboardShortcutEvent</span> &#123;</span><br><span class="line">  <span class="attr">key</span>: <span class="built_in">string</span>;</span><br><span class="line">  <span class="attr">metaKey</span>: <span class="built_in">boolean</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">getKeyboardShortcut</span>(<span class="params">e: KeyboardShortcutEvent</span>) &#123;&#125;</span><br></pre></td></tr></table></figure>

<p>测试代码现在只需要满足这个更小的接口，这使得它更加简洁。</p>
<p>我们的函数与全局<code>KeyboardEvent</code>类型的耦合也更少，可以在更多的上下文中使用。现在灵活多了。</p>
<p>这是不会报错的，因为结构类型<code>KeyboardEvent</code>可以分配给<code>KeyboardShortcutEvent</code>，因为它是一个超集，尽管<code>KeyboardEvent</code>有37个不相关的属性。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable language_">window</span>.<span class="title function_">addEventListener</span>(<span class="string">&quot;keydown&quot;</span>, <span class="function">(<span class="params">e: KeyboardEvent</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> shortcut = <span class="title function_">getKeyboardShortcut</span>(e); <span class="comment">// This is OK!</span></span><br><span class="line">  <span class="keyword">if</span> (shortcut) &#123;</span><br><span class="line">    <span class="title function_">execShortcut</span>(shortcut);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>Evan Martin在一篇精彩的文章中探讨了这个想法:<a target="_blank" rel="noopener" href="https://neugierig.org/software/blog/2019/11/interface-pattern.html">界面通常属于用户</a>。我强烈建议大家读一读!它改变了我编写和思考TypeScript代码的方式。</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/TypeScript/%E4%B8%BA%E4%BB%80%E4%B9%88Object-keys%E4%B8%8D%E8%83%BD%E6%AD%A3%E7%A1%AE%E5%9C%B0%E7%B1%BB%E5%9E%8B%E6%8E%A8%E5%AF%BC/" title="为什么Object.keys不能正确地类型推导">https://wyatex.online/TypeScript/为什么Object-keys不能正确地类型推导/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/TypeScript/" rel="tag"># TypeScript</a>
              <a href="/tags/%E7%BF%BB%E8%AF%91/" rel="tag"># 翻译</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%882%EF%BC%89%EF%BC%9A%E5%BC%80%E5%A7%8B%E7%BB%83%E4%B9%A0%E4%BD%93%E6%93%8D/" rel="prev" title="TypeScript黑魔法教学（2）：开始练习体操">
                  <i class="fa fa-angle-left"></i> TypeScript黑魔法教学（2）：开始练习体操
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/Rust/rust-build-js-runtime-1/" rel="next" title="用 Rust 构建你自己的 JavaScript 运行时实践（1）">
                  用 Rust 构建你自己的 JavaScript 运行时实践（1） <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
